package com.ptt.sqm.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.provider.MediaStore.Images.Media;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SlidingDrawer;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.drive.internal.ap;
import com.ptt.sqmonmobile.R;

public class WidgetUtil {

	public static void setNoDataRow(Context context, View view, int tableId, int colspan, boolean isEdit) {
		// TODO Auto-generated method stub
		TableLayout table = (TableLayout) view.findViewById(tableId);
		TableRow row = (TableRow) LayoutInflater.from(context).inflate(R.layout.no_row, null);
		TextView mNoData = (TextView) row.findViewById(R.id.no_data);
		TableRow.LayoutParams params = (TableRow.LayoutParams) mNoData.getLayoutParams();
		params.span = colspan; // amount of columns you will span
		mNoData.setLayoutParams(params);
		table.addView(row);
		table.requestLayout();

		if (isEdit) {
			CheckBox mCheck = (CheckBox) ((TableRow) table.getChildAt(0)).getChildAt(0);
			mCheck.setVisibility(CheckBox.INVISIBLE);
		}
	}

	public static void initDataRow(Context context, View view, int tableId, boolean isEdit) {
		// TODO Auto-generated method stub
		TableLayout table = (TableLayout) view.findViewById(tableId);
		TableRow row = (TableRow) table.findViewById(R.id.no_data_row);
		if (row != null) {
			table.removeView(row);
		}

		if (isEdit) {
			CheckBox mCheck = (CheckBox) ((TableRow) table.getChildAt(0)).getChildAt(0);
			mCheck.setVisibility(CheckBox.VISIBLE);
		}

		table.requestLayout();
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	public static void showProgress(final View view, final View progress, final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = view.getResources().getInteger(android.R.integer.config_shortAnimTime);

			view.setVisibility(show ? View.GONE : View.VISIBLE);
			view.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
				@Override
				public void onAnimationEnd(Animator animation) {
					view.setVisibility(show ? View.GONE : View.VISIBLE);
				}
			});

			progress.setVisibility(show ? View.VISIBLE : View.GONE);
			progress.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
				@Override
				public void onAnimationEnd(Animator animation) {
					progress.setVisibility(show ? View.VISIBLE : View.GONE);
				}
			});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			progress.setVisibility(show ? View.VISIBLE : View.GONE);
			view.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	public static void showSubProgress(final View view, final View progress, final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = view.getResources().getInteger(android.R.integer.config_shortAnimTime);

			LayoutParams param = progress.getLayoutParams();
			param.height = view.getHeight();

			progress.setVisibility(show ? View.VISIBLE : View.GONE);
			progress.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
				@Override
				public void onAnimationEnd(Animator animation) {
					progress.setVisibility(show ? View.VISIBLE : View.GONE);
				}
			});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			progress.setVisibility(show ? View.VISIBLE : View.GONE);
		}
	}

	public static void hideSoftKeyboard(Activity activity) {
		try {
			InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
			inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
		} catch (Exception e) {

		}
	}

	public static void setupSoftKeyboardClosed(final Activity activity, View view) {
		// Set up touch listener for non-text box views to hide keyboard.
		if (!(view instanceof EditText)) {

			view.setOnTouchListener(new OnTouchListener() {

				public boolean onTouch(View v, MotionEvent event) {
					hideSoftKeyboard(activity);
					return false;
				}

			});
		}

		// If a layout container, iterate over children and seed recursion.
		if (view instanceof ViewGroup) {

			for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {

				View innerView = ((ViewGroup) view).getChildAt(i);

				setupSoftKeyboardClosed(activity, innerView);
			}
		}

	}

	public static void setupSlideOpened(final Activity activity, View view, final SlidingDrawer slide) {

		if (view instanceof TableRow || view instanceof EditText || view instanceof TextView || view instanceof Button || view instanceof ImageView || view instanceof Spinner) {

			view.setClickable(false);
		}

		view.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub

				if (slide.getHeight() <= event.getRawY()) {
					slide.animateClose();
				}

				return false;
			}
		});

		// If a layout container, iterate over children and seed recursion.
		if (view instanceof ViewGroup) {

			for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {

				View innerView = ((ViewGroup) view).getChildAt(i);

				setupSlideOpened(activity, innerView, slide);
			}
		}

	}

	public static void setupSlideClosed(final Activity activity, View view) {

		// Set up touch listener for non-text box views to hide keyboard.
		if (view instanceof TableRow || view instanceof EditText || view instanceof TextView || view instanceof Button || view instanceof ImageView || view instanceof Spinner) {

			view.setClickable(true);
		}

		view.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub

				return false;
			}
		});

		// If a layout container, iterate over children and seed recursion.
		if (view instanceof ViewGroup) {

			for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {

				View innerView = ((ViewGroup) view).getChildAt(i);

				setupSlideClosed(activity, innerView);
			}
		}
	}

	public static void backPress(Activity activity) {
		FragmentManager fragmentManager = activity.getFragmentManager();
		if (activity.getFragmentManager().getBackStackEntryCount() != 0) {
			for (int index = fragmentManager.getBackStackEntryCount() - 1; index > -1; index--) {
				if (fragmentManager.getBackStackEntryAt(index).getName() != null) {
					String prevStack = fragmentManager.getBackStackEntryAt(index).getName();
					fragmentManager.popBackStack(prevStack, FragmentManager.POP_BACK_STACK_INCLUSIVE);
					break;
				}
			}

		}

	}

	public static void writeToFile(String filename, String data) {		
		try {
			File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_NOTIFICATIONS), filename);
			FileOutputStream fOut = new FileOutputStream(file);
			OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fOut);
			outputStreamWriter.write(data);
			outputStreamWriter.flush();
			outputStreamWriter.close();
		} catch (IOException e) {
			Log.e("Exception", "File write failed: " + e.toString());
		}
	}

	public static File getTempFile(Context context, String filename) {
		// it will return /sdcard/image.tmp
		// final File path = new
		// File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
		// context.getString(R.string.image_path));
		// if (!path.exists()) {
		// path.mkdir();
		// }
		// return new File(path, filename);

		File outputDir = context.getExternalCacheDir();
		return new File(outputDir, filename + ".tmp");

	}

	public static void bitmapToFile(Context context, Bitmap bitmap, String destinationFile) {

		File path = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), context.getString(R.string.image_path));
		if (!path.exists()) {
			path.mkdir();
		}

		try {
			File file = new File(path, destinationFile);
			FileOutputStream fOut = new FileOutputStream(file);

			bitmap.compress(Bitmap.CompressFormat.JPEG, 75, fOut);
			fOut.flush();
			fOut.close();
		} catch (Exception e) {
		}
	}

	public static void copyFile(Context context, String souceImagePath, String destinationFile) {

		File path = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), context.getString(R.string.image_path));
		if (!path.exists()) {
			path.mkdir();
		}

		try {
			File source = new File(souceImagePath);
			File destination = new File(path, destinationFile);
			if (source.exists()) {
				FileChannel src = new FileInputStream(source).getChannel();
				FileChannel dst = new FileOutputStream(destination).getChannel();
				dst.transferFrom(src, 0, src.size());
				src.close();
				dst.close();
			}

		} catch (Exception e) {
		}
	}

	public static Bitmap getImageOnDevice(Context context, String origFile) {
		// TODO Auto-generated method stub
		File output = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), context.getString(R.string.image_path) + AppUtil.PATH + origFile);
		if (output.exists()) {
			try {
				return Media.getBitmap(context.getContentResolver(), Uri.fromFile(output));
			} catch (FileNotFoundException e) {

			} catch (IOException e) {

			} catch (Exception e) {

			}
		}
		return null;
	}

	public static boolean deleteImageOnDevice(Context context, String file) {
		// TODO Auto-generated method stub
		boolean isSuccess = false;
		try {
			File output = new File(file);
			isSuccess = deleteImageOnDevice(context, output);
		} catch (Exception e) {

		}

		return isSuccess;

	}

	public static boolean deleteImageOnDevice(Context context, File file) {
		// TODO Auto-generated method stub
		boolean isSuccess = false;
		try {
			File output = file;
			if (output.exists()) {
				isSuccess = output.delete();
			}
		} catch (Exception e) {

		}

		return isSuccess;
	}

	public static Bitmap adjustImage(Bitmap origFile) {
		// TODO Auto-generated method stub
		// rotate image
		Matrix matrix = new Matrix();
		matrix.postRotate(90);
		origFile = Bitmap.createBitmap(origFile, 0, 0, (int) (origFile.getWidth()), (int) (origFile.getHeight()), matrix, true);

		// resize image
		origFile = Bitmap.createScaledBitmap(origFile, 480, 640, true);
		return origFile;
	}

	// check for internet connection
	public static boolean isNetworkEnabled(final Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getType() == ConnectivityManager.TYPE_WIFI) {

						WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

						if (!wm.isWifiEnabled()) {
							wm.setWifiEnabled(true);
						}

						break;
					} else if (info[i].getType() == ConnectivityManager.TYPE_MOBILE) {
						if (info[i].getState() != NetworkInfo.State.CONNECTED) {
							AlertDialog.Builder dialog = new AlertDialog.Builder(context);
							dialog.setMessage("Mobile Internet is closed");
							dialog.setPositiveButton("Setting", new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface paramDialogInterface, int paramInt) {
									// TODO Auto-generated method stub
									Intent myIntent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS);
									context.startActivity(myIntent);
									// get gps
								}
							});
							dialog.setNegativeButton("Discard", new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface paramDialogInterface, int paramInt) {
									// TODO Auto-generated method stub

								}
							});
							dialog.show();

							return false;
						}
					}

				}
			}
		}
		return true;
	}

	// check for internet connection
	public static boolean isNetworkAvailable(final Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivity.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected()) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean isLocationServiceAvailable(final Context context) {
		LocationManager lm = null;
		boolean gps_enabled = false, network_enabled = false;
		if (lm == null)
			lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		try {
			gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
		} catch (Exception ex) {
			return false;
		}
		try {
			network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		} catch (Exception ex) {
			return false;
		}

		if (network_enabled) {
			WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

			if (!wm.isWifiEnabled()) {
				wm.setWifiEnabled(true);
			}
		} else if (!gps_enabled) {
			AlertDialog.Builder dialog = new AlertDialog.Builder(context);
			dialog.setMessage("Location Servies is closed");
			dialog.setPositiveButton("Setting", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface paramDialogInterface, int paramInt) {
					// TODO Auto-generated method stub
					Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
					context.startActivity(myIntent);
					// get gps
				}
			});
			dialog.setNegativeButton("Discard", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface paramDialogInterface, int paramInt) {
					// TODO Auto-generated method stub

				}
			});
			dialog.show();
			return false;

		}
		return true;
	}

	public static void validateRequireData(final Context context, View inputView, final AlertDialog dialog, final List<View> errors) {
		// TODO Auto-generated method stub

		dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
		if (inputView instanceof EditText) {

			final EditText mEdit = (EditText) inputView;
			mEdit.setError(context.getString(R.string.alert_required_field));
			mEdit.addTextChangedListener(new TextWatcher() {

				public void afterTextChanged(Editable arg0) {
					// TODO Auto-generated method stub

				}

				@Override
				public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
					// TODO Auto-generated method stub
					if (arg0.toString().length() > 0) {
						mEdit.setError(null);
						dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);

						for (View errorView : errors) {
							EditText error = (EditText) errorView;
							if (error.getError() != null) {
								dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
								break;
							}
						}

					} else {
						dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
						mEdit.setError(context.getString(R.string.alert_required_field));
					}
				}

			});

		} else if (inputView instanceof Spinner) {

		} else if (inputView instanceof AutoCompleteTextView) {

		}

	}

	public static void validateMaxlengthData(final Context context, View inputView, final AlertDialog dialog, final int maxLength, final List<View> errors) {
		// TODO Auto-generated method stub
		if (inputView instanceof EditText) {

			final EditText mEdit = (EditText) inputView;
			mEdit.setError(null);
			mEdit.addTextChangedListener(new TextWatcher() {

				@Override
				public void afterTextChanged(Editable arg0) {
					// TODO Auto-generated method stub

				}

				@Override
				public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
					// TODO Auto-generated method stub
					if (arg0.toString().length() <= maxLength) {
						mEdit.setError(null);
						dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);

						for (View errorView : errors) {
							EditText error = (EditText) errorView;
							if (error.getError() != null) {
								dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
								break;
							}
						}

					} else {
						dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
						mEdit.setError(context.getString(R.string.alert_maxlength));
					}
				}

			});

		} else if (inputView instanceof Spinner) {

		} else if (inputView instanceof AutoCompleteTextView) {

		}
	}

	public static void validateNumericData(final Context context, View inputView, final AlertDialog dialog, final List<View> errors) {
		// TODO Auto-generated method stub

		dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
		if (inputView instanceof EditText) {

			final EditText mEdit = (EditText) inputView;
			mEdit.setError(context.getString(R.string.alert_isnumeric));
			mEdit.addTextChangedListener(new TextWatcher() {

				@Override
				public void afterTextChanged(Editable arg0) {
					// TODO Auto-generated method stub

				}

				@Override
				public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
					// TODO Auto-generated method stub
					Pattern pattern = Pattern.compile(".*[^0-9].*");
					if (!pattern.matcher(arg0).matches() && arg0.toString().length() > 0) {
						mEdit.setError(null);
						dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);

						for (View errorView : errors) {
							EditText error = (EditText) errorView;
							if (error.getError() != null) {
								dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
								break;
							}
						}

					} else {
						dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
						mEdit.setError(context.getString(R.string.alert_isnumeric));
					}
				}

			});

		} else if (inputView instanceof Spinner) {

		} else if (inputView instanceof AutoCompleteTextView) {

		}
	}

	public static void validateEmail(final Context context, View inputView, final AlertDialog dialog, final List<View> errors) {
		// TODO Auto-generated method stub

		String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

		final Pattern pattern = Pattern.compile(EMAIL_PATTERN);
		dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
		if (inputView instanceof EditText) {

			final EditText mEdit = (EditText) inputView;
			if (pattern.matcher(mEdit.getText().toString()).matches() && mEdit.getText().toString().toString().length() > 0) {
				mEdit.setError(null);
				dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);

				for (View errorView : errors) {
					EditText error = (EditText) errorView;
					if (error.getError() != null) {
						dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
						break;
					}
				}

			} else {
				dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
				mEdit.setError(context.getString(R.string.alert_isemail));
			}

			mEdit.addTextChangedListener(new TextWatcher() {

				@Override
				public void afterTextChanged(Editable arg0) {
					// TODO Auto-generated method stub

				}

				@Override
				public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
					// TODO Auto-generated method stub

					if (pattern.matcher(arg0).matches() && arg0.toString().length() > 0) {
						mEdit.setError(null);
						dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);

						for (View errorView : errors) {
							EditText error = (EditText) errorView;
							if (error.getError() != null) {
								dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
								break;
							}
						}

					} else {
						dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
						mEdit.setError(context.getString(R.string.alert_isemail));
					}
				}

			});

		} else if (inputView instanceof Spinner) {

		} else if (inputView instanceof AutoCompleteTextView) {

		}
	}
}
